#include "widget.h"
#include "ui_widget.h"
#include <QPixmap>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QTcpSocket(this);
    face = new Interface;
    face ->setLoginInterface(this);
    QObject::connect(client, &QTcpSocket::readyRead, this, &Widget::onReadyRead);
    face->setClient(client);
    QFile qssFile(":/qss/style.qss");  // QSS文件路径
    if (qssFile.open(QFile::ReadOnly | QFile::Text)) {
        QTextStream stream(&qssFile);
        this->setStyleSheet(stream.readAll());  // 设置给整个应用
        qssFile.close();
    }

    // 方法2：使用QPainter进行高质量绘制（推荐）
    QPixmap originalPixmap(":/qss/logo.png");
    if(!originalPixmap.isNull()) {
        QPixmap scaledPixmap = originalPixmap.scaled(
            ui->icon->width(),
            ui->icon->height(),
            Qt::KeepAspectRatio,
            Qt::SmoothTransformation
            );
        ui->icon->setPixmap(scaledPixmap);
        // 设置对齐方式为居中
        ui->icon->setAlignment(Qt::AlignCenter);

        // 设置大小策略
        ui->icon->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        // 可选：设置固定大小或最小大小
        ui->icon->setMinimumSize(1000, 1000); // 根据你的需求调整

        // 设置图标
        QIcon connecticon(":/icon/connect.png");
        ui->pushButton_connect->setIcon(connecticon);

        // 设置图标大小（可选）
        ui->pushButton_connect->setIconSize(QSize(32, 32));

        // 移除按钮文本
        ui->pushButton_connect->setText("");

        // 可选：设置按钮大小
        ui->pushButton_connect->setFixedSize(40, 40);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::handleLoginResponse(const Pack &pack)
{
    switch(pack.getType()) {
    case TYPE_REGIST:{
        if(pack.getBack() == BACK_SUCCESS){
            QMessageBox::information(this,"注册","注册成功");
        }else{
            QMessageBox::critical(this,"注册","该账号已存在");
        }
        break;
    }
    case TYPE_LOGIN:{
        if(pack.getBack() == BACK_SUCCESS){
            QMessageBox::information(this,"登录","登录成功");

            face->show();
            this->hide();
        }else{
            QMessageBox::critical(this,"登录","账号或密码错误");
        }
        break;
    }
    }
}

bool Widget::eventFilter(QObject *obj, QEvent *event)
{
    if (obj->objectName() == "imageLabel" && event->type() == QEvent::Resize) {
        QLabel *label = qobject_cast<QLabel*>(obj);
        if (label && !label->pixmap().isNull()) {
            // 重新缩放图片以适应新的QLabel大小
            label->setPixmap(label->pixmap().scaled(
                label->size(),
                Qt::KeepAspectRatio,
                Qt::SmoothTransformation
                ));
        }
    }
    return QWidget::eventFilter(obj, event);
}

Interface *Widget::getInterface()
{
    return face;
}

void Widget::on_pushButton_connect_clicked()
{
    ip.setAddress(ui->lineEdit_ip->text());
    port = ui->lineEdit_port->text().toInt();
    client->connectToHost(ip,port);
    if(client->waitForConnected(2000)){
        //如果2秒内连接上服务器
        QMessageBox::information(this,"连接","连接服务器成功");
    }else{
        QMessageBox::warning(this,"连接","连接失败，请检查网络");
    }
}

void Widget::on_pushButton_login_clicked()
{
    qDebug() << "登录按钮被点击";
    // 检查当前socket状态，仅在未连接时发起连接
    if (client->state() != QTcpSocket::ConnectedState) {
        ip.setAddress(ui->lineEdit_ip->text());
        port = ui->lineEdit_port->text().toInt();
        client->connectToHost(ip, port);

        // 等待连接结果（超时2秒）
        if (!client->waitForConnected(2000)) {
            QMessageBox::warning(this, "连接", "连接失败，请检查网络");
            return;
        }
    }
    // 连接成功后发送登录数据
    QString name = ui->lineEdit_name->text();
    QString pswd = ui->lineEdit_password->text();
    Pack pack;

    pack.setType(TYPE_LOGIN);
    pack << name << pswd;
    pack >> client;
}

void Widget::onReadyRead()
{
    while(client->bytesAvailable()) {
        int res = 0;
        int size = 0;
        Pack pack;



        if(unreaded_pack_size != 0){
            res = client->read((char*)&readed_pack + readed_pack_size,unreaded_pack_size);
            if(res != unreaded_pack_size){
                // 这里只要更新下已读大小和未读大小，保证下一次进入当前分支的时候，能够根据已读大小和未读大小，读取对应的数据以及存放到对应的地方
                readed_pack_size += res;
                unreaded_pack_size -= res;
                break;
            }

            pack = readed_pack;
            // 处理完分包记得 unreaded_pack_size = 0;
            unreaded_pack_size = 0;
        }else{

            if(unreaded_size_size != 0){
                client->read((char*)&readed_size + readed_size_size,unreaded_size_size);
                size = readed_size;
                unreaded_size_size = 0;
            }else{

                // else 部分为正常读取数据：先读4字节，再读剩余字节数，可能处理分包
                res = client->read((char*)&size,4);
                if(res == 0){break;}

                if(res != 4){
                    readed_size = size;
                    readed_size_size = res;
                    unreaded_size_size = 4 - res;
                    break;
                }
            }


            res = client->read((char*)&pack+4,size-4);
            if(res == 0){break;}

            pack.setSize(size);


            if(res != size-4){
                // 如果实际读取到的字节数 != 想要读取的字节数
                // 说明发生了分包
                readed_pack = pack;// 将已经读取的协议包缓存在每个客户端专属的缓存区 readed_pack 里面
                readed_pack_size = res + 4;
                unreaded_pack_size = size - readed_pack_size;
                break;
            }
        }
        switch(pack.getType()){
        case TYPE_REGIST:
        case TYPE_LOGIN:
        {
            handleLoginResponse(pack);
            break;
        }
        case TYPE_TEM_HUM:
        {
            QStringList val=pack.readAll();
            //qDebug()<<val[0];
            this->getInterface()->setLineEdit(val[0]);
            break;
        }
        case TYPE_HEART:
        {
            QStringList val=pack.readAll();
            //qDebug()<<val[0];
            this->getInterface()->setLineEdit_bpm(val[0]);
            break;
        }
        case TYPE_ERROR:
        {
            QStringList val=pack.readAll();
            //qDebug()<<val[0];
            this->getInterface()->setLineEdit_errmsg(val[0]);
            break;
        }
        case TYPE_DETECTED:
        {
            this->getInterface()->setlabel_detected(1);
            break;
        }
        case TYPE_AWAY:
        {
            this->getInterface()->setlabel_detected(2);
            break;
        }
        case TYPE_LUX:
        {
            QStringList val=pack.readAll();
            //qDebug()<<val[0];
            this->getInterface()->setlabel_lux(val[0]);
            break;
        }
        case TYPE_ORDER:
            break;
        case TYPE_NOMCU:
        {
            QMessageBox::warning(this,"发送指令失败","当前无被控端连接");
            break;
        }
        }
    }
}


void Widget::on_pushButton_register_clicked()
{
    // 检查当前socket状态，仅在未连接时发起连接
    if (client->state() != QTcpSocket::ConnectedState) {
        ip.setAddress(ui->lineEdit_ip->text());
        port = ui->lineEdit_port->text().toInt();
        client->connectToHost(ip, port);

        // 等待连接结果（超时2秒）
        if (!client->waitForConnected(2000)) {
            QMessageBox::warning(this, "连接", "连接失败，请检查网络");
            return;
        }
    }

    // 连接成功后发送注册数据
    QString name = ui->lineEdit_name->text();
    QString pswd = ui->lineEdit_password->text();
    Pack pack;

    pack.setType(TYPE_REGIST);
    pack << name << pswd;
    pack >> client;
}

